import 'package:event_bus/event_bus.dart';
import 'package:flutter/cupertino.dart';
import 'package:yp/config/config.dart';
import 'package:yp/config/event_bus.dart';
import 'package:yp/config/index.dart';
import 'package:yp/helper.dart';
import 'package:yp/pages/main/logic.dart';
import 'package:yp/services/api.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'dart:convert' as convert;

import 'state.dart';

import 'package:yp/pages/address_selector/address_model.dart';

class ClassificationLogic extends GetxController {
  final state = ClassificationState();
  int currentPage = 0;
  int pageSize = 20;
  // final MainAppLogic mainAppLogics = Get.put(MainAppLogic());
  final MainLogic mainLogic = Get.put(MainLogic());
  var shopInfo;

  @override
  void onInit() {
    super.onInit();

    shopInfo = SpUtil.getObject(Config.GET_SHOP_INFO) ?? {};
    if (SpUtil.getInt(Config.IS_CHANGE_SHOP) == 1) {
      // if (state.templateNumId == '' &&
      //     SpUtil.getString('template_num_id') == '') {
      if (state.templateNumId == '') {
        var params = {
          "channel_num_id": 99,
          "use_platform": 2,
          "tmpl_platform_type": "2",
          "ec_shop_num_id": shopInfo['shop_id'],
          "tmpl_type": "6",
        };
        Api.homeTemplate(params).listen((event) async {
          if (event['instance'] == null) {
            return;
          }
          List dataList = event['instance']['data'];
          if (dataList == null ||
              dataList.isEmpty ||
              dataList[0]['widgets_data_params'] == null) {
            toast('未能获取到分类模板信息');
          }
          if (!dataList[0]['widgets_data_params']
              .toString()
              .contains('template_num_id')) {
            toast('未能获取到分类模板ID');
          }
          params = convert.jsonDecode(dataList[0]['widgets_data_params']);
          state.templateNumId = params['template_num_id'].toString();
          await SpUtil.putString('template_num_id', state.templateNumId);
          // 第三方店铺需要加载分类
          getGoodsCategories();
        });
      } else {
        // 第三方店铺需要加载分类
        getGoodsCategories();
      }
    }
  }

  void requestGoodsCategories() {
    EasyLoading.show();
    var params = {
      "tmpl_platform_type": "2",
      "ec_shop_num_id": shopInfo['shop_id'],
      "tmpl_type": "6",
    };
    Api.homeTemplate(params).listen((event) {
      if (event['code'] == 0) {
        if (event['instance'] == null) {
          EasyLoading.dismiss();
          return;
        }
        List dataList = event['instance']['data'];
        if (dataList == null ||
            dataList.isEmpty ||
            dataList[0]['widgets_data_params'] == null) {
          toast('未能获取到分类模板信息');
        }
        if (!dataList[0]['widgets_data_params']
            .toString()
            .contains('template_num_id')) {
          toast('未能获取到分类模板ID');
        }
        params = convert.jsonDecode(dataList[0]['widgets_data_params']);
        state.templateNumId = params['template_num_id'].toString();
        SpUtil.putString('template_num_id', state.templateNumId);
        state.layout = params['layout'].toString();
        getGoodsCategories();
        // params = {
        //   "template_type": 2,
        //   "template_num_id": state.templateNumId,
        //   // "shop_id": SpUtil.getInt('storeShopNum'),
        //   "shop_id": shopInfo['shop_id'],
        // };
        // Api.goodsCategories(params).listen((event) {
        //   if (event['code'] == 0) {
        //     List categoryList = event['categorys'];
        //     if (categoryList != null && categoryList.isNotEmpty) {
        //       state.categoryList = categoryList;
        //       for (var category in state.categoryList) {
        //         category['globalKey'] = GlobalKey();
        //       }
        //       if (state.isStandardLayout() || state.isShopWindowLayout()) {
        //         EasyLoading.dismiss();
        //         update();
        //       } else if (state.isUniversalLayout()) {
        //         update();
        //         requestGoodsList(1);
        //       }
        //     } else {
        //       EasyLoading.dismiss();
        //       update();
        //     }
        //   } else {
        //     EasyLoading.dismiss();
        //     update();
        //   }
        // }, onError: (error) {
        //   EasyLoading.dismiss();
        //   print('++++++++goodsCategories++++++++失败 ***************');
        // });
      } else {
        EasyLoading.dismiss();
      }
    }, onError: (error) {
      EasyLoading.dismiss();
      print('++++++++homeTemplate++++++++失败 ***************');
    });
  }

  void requestGoodsList(int pageNo) {
    getCurrentLocationInfo(success: (data) {
      var addressInfo = data['addressInfo'];
      if (state.categoryList == null || state.categoryList.isEmpty) {
        EasyLoading.dismiss();
        update();
        return;
      }
      var categoryJson = state.categoryList[state.level1ChooseIndex];
      List level2CategoryList = categoryJson['child_list'];
      var virtualParentId = categoryJson['cat_id'];
      var virtualCatId = "";
      if (level2CategoryList == null || level2CategoryList.isEmpty) {
        EasyLoading.dismiss();
        update();
        return;
      }
      virtualCatId = level2CategoryList[state.level2ChooseIndex]['cat_id'];
      var params = {
        "data_sign": 0,
        "channel_num_id": 98,
        "order_by": state.getOrderByParams(),
        "shop_id": shopInfo['shop_id'],
        "virtual_cat_id": virtualCatId,
        "virtual_parent_id": virtualParentId,
        "use_platform": 2,
        "customer_type": 3,
        "user_num_id": SpUtil.getInt('empeNumId'),
        "page_no": pageNo,
        "page_size": pageSize,
        "prv_num_id": addressInfo['prv_num_id'],
        "city_num_id": addressInfo['city_num_id'],
        "city_area_num_id": addressInfo['city_area_num_id'],
        "town_num_id": addressInfo['town_num_id'],
        "maplocation_x": addressInfo['maplocation_x'],
        "maplocation_y": addressInfo['maplocation_y'],
      };
      var locationJson = SpUtil.getObject(Config.USER_CURRENT_LOCATION);
      if (locationJson != null && locationJson['cityCode'] != null) {
        params['city_num_id'] = locationJson['cityCode'];
      }

      Api.goodsList(params).listen((event) {
        EasyLoading.dismiss();
        state.refreshController.loadComplete();
        if (event['code'] == 0) {
          currentPage = pageNo;
          if (pageNo == 1 &&
              state.goodsList != null &&
              state.goodsList.isNotEmpty) {
            state.goodsList.clear();
          }
          if (state.goodsList == null) {
            state.goodsList = [];
          }
          List list = event['lists'];
          if (list != null && list.isNotEmpty) {
            state.goodsList.addAll(list);
          } else {
            state.refreshController.loadNoData();
          }
          // if (list == null || list.isEmpty || list.length < pageSize) {
          //   state.refreshController.loadNoData();
          // }
        }
        update();
      }, onError: (error) {
        EasyLoading.dismiss();
        print('失败+++++++goodsList++++++ error = $error');
      });
    });
  }

  void onLoadMoreGoodsList() {
    requestGoodsList(currentPage + 1);
  }

  void requestAddGoods(String ecShopNumId, String itemNumId, String styleNumId,
      String ecStyleNumId) {
    var params = {
      "use_platform": 2,
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "emp_num_id": 0,
      "channel_num_id": 99,
      "quantity": 1.0,
      "ec_shop_num_id": ecShopNumId,
      "item_num_id": itemNumId,
      "style_num_id": styleNumId,
      "ec_style_num_id": ecStyleNumId,
      'access_token': SpUtil.getString('token'),
    };
    Api.addShoppingCart(params).listen((event) {
      if (event['code'] == 0) {
        mainLogic.getCartNum();
        toast('添加成功');
      } else {
        toast(event['message']);
      }
    });
  }

  void getGoodsCategories() {
    var params = {
      "template_type": 2,
      "template_num_id": state.templateNumId == ''
          ? SpUtil.getString('template_num_id')
          : state.templateNumId,
      // "shop_id": SpUtil.getInt('storeShopNum'),
      "shop_id": shopInfo['shop_id'],
    };
    Api.goodsCategories(params).listen((event) {
      if (event['code'] == 0) {
        List categoryList = event['categorys'];
        if (categoryList != null && categoryList.isNotEmpty) {
          state.categoryList = categoryList;
          for (var category in state.categoryList) {
            category['globalKey'] = GlobalKey();
          }
          if (state.isStandardLayout() || state.isShopWindowLayout()) {
            EasyLoading.dismiss();
            update();
          } else if (state.isUniversalLayout()) {
            update();
            requestGoodsList(1);
          }
        } else {
          EasyLoading.dismiss();
          update();
        }
      } else {
        EasyLoading.dismiss();
        update();
      }
    }, onError: (error) {
      EasyLoading.dismiss();
      print('++++++++goodsCategories++++++++失败 ***************');
    });
  }
}
